<template>
	<div class="company-container">
		<div class="company-bottom">
			<el-card>
				<template #header>
					<div style="display: flex;justify-content: space-between;">
						<div class="card-header" style="font-size: 24px;font-weight: 550;">
							<span>公司列表</span>
						</div>
						<div>
							<el-icon :size="28" @click="newCompany">
								<Plus />
							</el-icon>
						</div>
					</div>
				</template>

				<div class="search-form" style="margin-bottom: 16px; display: flex; gap: 20px; align-items: center;">
					<el-form :model="searchForm" inline>
						<!-- 公司名称筛选 -->
						<el-form-item label="公司名称">
							<el-input v-model="searchForm.companyName" placeholder="请输入公司名称" style="width: 200px;"
								clearable 
								/>
						</el-form-item>

						<!-- 过磅类型筛选 -->
						<el-form-item label="过磅类型">
							<el-select v-model="searchForm.companyType" placeholder="请选择过磅类型" style="width: 160px;"
								clearable 
								>
								<el-option label="采购" :value="1"></el-option>
								<el-option label="销售" :value="2"></el-option>
							</el-select>
						</el-form-item>

						<!-- 筛选按钮组 -->
						<el-form-item>
							<el-button type="primary" @click="handleSearch">查询</el-button>
							<el-button @click="handleResetSearch">重置</el-button>
						</el-form-item>
					</el-form>
				</div>

				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="createTime" label="创建时间" width="200" />
					<el-table-column prop="companyName" label="公司名称" />
					<el-table-column prop="companyType" label="过磅类型" width="100">
						<template #default="scope">
							{{ scope.row.companyType === 1 ? '采购' : '销售' }}
						</template>
					</el-table-column>
					<el-table-column prop="roughWeight" label="毛重扣重" width="100" />
					<el-table-column prop="tare" label="皮重扣重" width="100" />
					<el-table-column prop="suttle" label="结算净重" width="100" />
					<el-table-column label="操作" width="150" fixed="right">
						<template #default="scope">
							<el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
							<el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="total>0" v-model:current-page="listQuery.current"
						v-model:page-size="listQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>
		</div>

		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
			<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item label="公司名称" prop="companyName">
					<el-input v-model="formData.companyName" placeholder="请输入公司名称" style="width: 180px;" />
				</el-form-item>

				<el-form-item label="过磅类型" prop="companyType">
					<el-select v-model="formData.companyType" placeholder="请选择过磅类型" style="width:180px;">
						<el-option label="采购" :value="1"></el-option>
						<el-option label="销售" :value="2"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="毛重扣重" prop="roughWeight">
					<el-input-number v-model="formData.roughWeight" :min="-9999" :max="9999" :precision="3"
						:step="0.001" controls-position="right" placeholder="±值" style="width: 180px;" />
					<span style="margin-left: 8px; color: #666;">吨（±值）</span>
				</el-form-item>

				<el-form-item label="皮重扣重" prop="tare">
					<el-input-number v-model="formData.tare" :min="-9999" :max="9999" :precision="3" :step="0.001"
						controls-position="right" placeholder="±值" style="width: 180px;" />
					<span style="margin-left: 8px; color: #666;">吨（±值）</span>
				</el-form-item>

				<el-form-item label="结算净重" prop="suttle">
					<el-input-number v-model="formData.suttle" :min="0.001" :max="10" :precision="3" :step="0.001"
						controls-position="right" placeholder="结算系数" style="width: 180px;" />
					<span style="margin-left: 8px; color: #666;">系数（0.001-1）</span>
				</el-form-item>
				<el-form-item label="打印入库模版" prop="storeModelId">
					<el-select v-model="formData.storeModelId" placeholder="请选择磅单类型" style="width: 180px;">
						<el-option label="盛虹入库" :value="1"></el-option>

						<el-option label="天津大港入库" :value="3"></el-option>
						<el-option label="中石油燃料油" :value="6"></el-option>
						<el-option label="元氏九天/砾乐风" :value="7"></el-option>
						<el-option label="默认磅单" :value="5"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="打印出库模版" prop="outModelId">
					<el-select v-model="formData.outModelId" placeholder="请选择磅单类型" style="width: 180px;">

						<el-option label="盛虹出库" :value="2"></el-option>

						<el-option label="天津大港出库" :value="4"></el-option>
						<el-option label="中石油燃料油" :value="6"></el-option>
						<el-option label="元氏九天/砾乐风" :value="7"></el-option>
						<el-option label="默认磅单" :value="5"></el-option>
					</el-select>
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button @click="resetForm(formRef)">取消</el-button>
				<el-button type="primary" @click="handleSubmit">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

	const size = ref<ComponentSize>('default')
	import { Plus } from '@element-plus/icons-vue'

	const { proxy } = getCurrentInstance() as any;
	const dialogVisible = ref(false)
	const formRef = ref<FormInstance>()
	const dialogTitle = ref('新增公司')
	const currentEditId = ref<number | null>(null)
	const actionType = ref('add')

	interface CompanyData {
		id ?: number | null;
		createTime ?: string;
		companyName : string;
		companyType : number;
		roughWeight : number;
		tare : number;
		suttle : number;
		outModelId : number;
		storeModelId : number;
	}

	const defaultFormData : CompanyData = {
		id: null,
		companyName: '',
		companyType: null,
		roughWeight: 0,
		tare: 0,
		suttle: 1,
		outModelId: 5,
		storeModelId: 5
	}

	const formData = reactive<CompanyData>({ ...defaultFormData })

	const rules = reactive<FormRules>({
		companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
		companyType: [{ required: true, message: '请选择过磅类型', trigger: 'change' }],
		roughWeight: [
			{
				required: true,
				validator: (_, value, callback) => {
					if (value === null || value === undefined) {
						callback(new Error('请输入毛重扣重值'))
					} else if (value < -9999 || value > 9999) {
						callback(new Error('毛重扣重范围：-9999 ~ 9999'))
					} else {
						callback()
					}
				},
				trigger: 'blur'
			}
		],
		tare: [
			{
				required: true,
				validator: (_, value, callback) => {
					if (value === null || value === undefined) {
						callback(new Error('请输入皮重扣重值'))
					} else if (value < -9999 || value > 9999) {
						callback(new Error('皮重扣重范围：-9999 ~ 9999'))
					} else {
						callback()
					}
				},
				trigger: 'blur'
			}
		],
		suttle: [
			{
				required: true,
				validator: (_, value, callback) => {
					if (value === null || value === undefined) {
						callback(new Error('请输入结算系数'))
					} else if (value < 0.001 || value > 10) {
						callback(new Error('结算系数范围：0.001 ~ 1'))
					} else {
						callback()
					}
				},
				trigger: 'blur'
			}
		]
	})

	// 重置表单
	const resetForm = () => {
		formRef.value?.resetFields()
		Object.assign(formData, defaultFormData)
		dialogVisible.value = false
	}

	// 编辑按钮点击
	const handleEdit = (row : CompanyData) => {
		actionType.value = 'edit'
		dialogTitle.value = '编辑公司'
		currentEditId.value = row.id || null

		// 填充表单数据
		Object.keys(formData).forEach(key => {
			if (row.hasOwnProperty(key)) {
				// 处理需要转换的字段
				if (['storeModelId', 'outModelId'].includes(key)) {
					formData[key] = Number(row[key]) || 5
				} else {
					formData[key] = row[key]
				}
			}
		})
		dialogVisible.value = true
	}

	const handleDelete = (row : CompanyData) => {
		ElMessageBox.confirm('确定要删除该公司吗？', '删除确认', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
			try {
				try {
					const res = await proxy.$request.deleteCompany({ id: row.id })
					if (res.data.code === 200) {
						ElMessage.success('删除成功!')
						fetchData()
					} else {
						ElMessage.error(res.data.message || '删除失败')
					}
				} catch (error) {
					console.error('删除失败:', error)
					ElMessage.error('删除失败，请稍后重试')
				}
			} catch (error) {
				console.error('删除失败:', error)
				ElMessage.error('删除失败，请稍后重试')
			}
		}).catch(() => {
			// 用户取消删除
		})
	}

	const filterEmptyFields = (obj : any) => {
		return Object.entries(obj).reduce((acc, [key, value]) => {
			if (value !== '' && value !== null && value !== undefined) {
				acc[key] = value
			}
			return acc
		}, {})
	}

	const handleSubmit = async () => {
		try {
			await formRef.value?.validate()
			// 验证通过后的提交逻辑
			console.log('提交数据:', formData)
			// const matchingCargo = cargoOptions.value.find(
			//    (cargo) => cargo.cargoName === formData.cargoName
			//  );
			// formData.deductingId =  matchingCargo?.id && !/[\u4e00-\u9fa5]/.test(matchingCargo.id)  ? matchingCargo.id : 0;

			proxy.$request.setCompany(filterEmptyFields(formData)).then((res => {

				if (res.data.code === 200) {

					ElMessage.success(res.data.message)

					const formEl = formRef.value
					resetForm()
					fetchData()

				} else {

					ElMessage.error(res.data.message)
				}
			})).catch((err => {
				console.log('err', err)
				ElMessage.error(err.data.message);
			}))


			// dialogVisible.value = false
		} catch (error) {
			console.log('表单验证失败:', error)
		}
	}

	const newCompany = () => {
		actionType.value = 'add'
		dialogTitle.value = '新增公司'
		resetForm()
		dialogVisible.value = true
	}

	const tableData = ref<CompanyData[]>([])

	interface ListQuery extends Record<string, any> {
		current : number;
		size : number;
		companyName ?: string; // 新增：公司名称筛选
		companyType ?: number; // 新增：过磅类型筛选（1=采购，2=销售）
	}

	// 2. 替换原有listQuery定义，使用扩展后的类型
	const listQuery = reactive<ListQuery>({
		current: 1,
		size: 5,
		companyName: undefined, // 初始化为undefined（无筛选）
		companyType: undefined  // 初始化为undefined（无筛选）
	});
	const searchForm = reactive({
		companyName: '',
		companyType: undefined as number | undefined
	});

	const total = ref(0)
	const handleSearch = () => {
		// 1. 同步筛选条件到查询参数（仅传递非空/非undefined的值）
		listQuery.companyName = searchForm.companyName.trim() || undefined; // 去除空格，空字符串则设为undefined
		listQuery.companyType = searchForm.companyType; // 下拉框清空时为undefined，无需额外处理

		// 2. 筛选时重置页码为1（避免筛选后页码超出结果页数）
		listQuery.current = 1;

		// 3. 携带筛选条件请求接口
		fetchData();
	};
	const handleResetSearch = () => {
		// 1. 清空搜索表单
		searchForm.companyName = '';
		searchForm.companyType = undefined;

		// 2. 清空listQuery中的筛选字段
		listQuery.companyName = undefined;
		listQuery.companyType = undefined;

		// 3. 重置页码为1，重新请求默认数据
		listQuery.current = 1;
		fetchData();
	};

	const fetchData = async () => {
		try {
			// 此时listQuery已包含 companyName 和 companyType 筛选字段（非筛选时为undefined）
			const res = await proxy.$request.getCompanyList(listQuery);

			if (res?.data?.code === 200) {
				tableData.value = res.data.result?.resultData || [];
				total.value = res.data.result?.totalRows || 0;
			} else {
				ElMessage.error(res?.data?.message || '请求失败');
			}
		} catch (error : any) {
			console.error('API请求错误:', error);
			ElMessage.error(error.message || '网络请求异常');
		}
	};

	const handleSizeChange = (val : number) => {
		listQuery.size = val
		listQuery.current = 1
		fetchData()
	}

	const handleCurrentChange = (val : number) => {
		listQuery.current = val
		fetchData()
	}

	onMounted(() => {
		fetchData()
	})
</script>

<style lang="scss" scoped>
	.company-container {
		padding: 28px;
		box-sizing: border-box;
		position: relative;

		.company-bottom {
			width: 100%;
			margin-top: 50px;
		}
	}
</style>